﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using BusinessLogic;
using BusinessObject;
using Utility;
using System.Web.Security;
using System.Resources;
namespace WebTeamplate
{


    public partial class Admin_GenaretaBarcode : BasePage
    {
        public string nguoiNhap = string.Empty;
        public string kho = string.Empty;
        public PhieuNhapHang objPhieuNhapHang = new PhieuNhapHang();
        public Int64 MaPhieuPhap
        {

            get
            {
                object o = ViewState["MaPhieuPhap"];
                if (o != null) return (Int64)o;
                return Int64.MinValue;
            }

            set { ViewState["MaPhieuPhap"] = value; }

        }
        #region Init,Load
        protected void Page_Load(object sender, EventArgs e)
        {
        
            //  ClientDefaultButton.SetPageDefaultButton(this.Page, btnSearch.ClientID);
            if (!Page.IsPostBack)
            {             
                InitParamater();
                LoadData();
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }
        private void InitParamater()
        {
            MaPhieuPhap = ConvertValueObject.ParseInt(CommonFunction.GetValueFromQueryString(this.Page, "id"));
        }
        #endregion

        #region Methods

        public void LoadData()
        {
            hidListId.Value = string.Empty;
            hidListIdSelect.Value = string.Empty;
            objPhieuNhapHang = PhieuNhapHangUtil.Get(this.MaPhieuPhap);
            if (objPhieuNhapHang != null)
            {
                MembershipUser member = Membership.GetUser(objPhieuNhapHang.NguoiNhap);
                if (member != null)
                {
                    UserProfile objProfile = UserProfileUtil.Get(this.applicationName, new Guid(member.ProviderUserKey.ToString()));
                    if (objProfile != null)
                        nguoiNhap = objProfile.Name;
                    else nguoiNhap = objPhieuNhapHang.NguoiNhap;
                }
                else nguoiNhap = objPhieuNhapHang.NguoiNhap;
                //get Kho
                SubCategory objKho = SubCategoryUtil.Get(objPhieuNhapHang.MaKho, CommonFunction.DEFAULT_WAREHOUSE_CODE);
                kho = objKho.SubCategoryName;
                //get List Data
                List<ChiTietPhieuNhapHangDetail> lstChiTiet = ChiTietPhieuNhapHangUtil.GetChiTietPhieuNhapHangDetailByMaPhieuNhapHang(this.MaPhieuPhap);
                //generate form here
                rptData.DataSource = lstChiTiet;
                rptData.DataBind();
                hidListIdSelect.Value = hidListId.Value;
            }
        }

        #endregion

        #region Events,Handler

        protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ChiTietPhieuNhapHangDetail cate = (ChiTietPhieuNhapHangDetail)e.Item.DataItem;
                if (cate == null)
                    return;
                Curency objCurency = CurencyUtil.Get(cate.CurencyCode);
                hidListId.Value += cate.MaMatHang + ";";
                Literal ltr = (Literal)e.Item.FindControl("ltrGia");
                ltr.Text = ConvertValueObject.ParseString(cate.GiaNhap) + " " + objCurency.Name; 
            }
        }
        
        #endregion

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            Response.Redirect("ChiTietPhieuNhapHang.aspx?id=" + this.MaPhieuPhap + "&act=edit");
        }
        protected void btnPrint_Click(object sender,EventArgs e)
        {
            Response.Redirect("ViewPhieuNhapHang.aspx?id=" + this.MaPhieuPhap);
        }
        protected void btnCancel_Click(object sender,EventArgs e)
        {
            Response.Redirect("DMPhieuNhapHang.aspx");
        }
        protected void btnExportBarCode_Click(object sender, EventArgs e)
        {
            string[] arrId =hidListIdSelect.Value.Split(';');
            string[] arrSL =hidListSoLuong.Value.Split(';');
            Session.Add("idBarCode", hidListIdSelect.Value);
            Session["slBarCode"] = hidListSoLuong.Value;           
            if (arrId.Length > 0)
            {
                //delete all barcode
                string s = Server.MapPath("~/Admin/BarCode/Images/");
                string[] filePaths = Directory.GetFiles(s);
                foreach (string filePath in filePaths)
                {
                    try
                    {
                        File.Delete(filePath);
                    }
                    catch
                    {
                    }
                }

                for (int i = 0; i < arrId.Length; i++)
                {
                    if (arrId[i].ToString() != string.Empty)
                    {
                        string maMatHang = arrId[i].ToString();
                        int soluong = ConvertValueObject.ParseInt(arrSL[i].ToString());
                        if (soluong > 0)
                            // CreateBarcode391(maMatHang, "2.300");
                            ExportBarCode128(maMatHang, "5000");


                    }
                }
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenPopUpBarCode", "OpenPopUpBarCode();", true);
           
        }
        public string GetXe(string maxe)
        {
            DMXe objXe = DMXeUtil.Get(ConvertValueObject.ParseInt(maxe));
            if (objXe != null)
                return objXe.TenXe;
            else return string.Empty;
        }
        private void CreateBarcode39(string requestedCode,string price)
        {
            //  return;
            const int PaddingTop = 0;            
            string barcodeText = null;
            barcodeText = "*" + requestedCode.Trim() + "*";           
            // Initialize values
            int barcodeFontSize = 30;
            int numericFontSize = 10;
            int width = 160;
            int height = 80;
            // Create bitmap
            Bitmap bmp = new Bitmap(width, height);
            // Create surface
            Graphics gfx = Graphics.FromImage(bmp);
            gfx.Clear(Color.White);
            // Set render mode
            gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
            // Set brush type and color
            Brush b = Brushes.Black;
            // Load EAN font
            string sss = Server.MapPath("~/Admin/BarCode/Font/FREE3OF9.TTF");
            System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
            pfc.AddFontFile(sss);
            // Write barcode
            FontFamily ff = pfc.Families[0];
            Font f = new Font(ff, barcodeFontSize);
            SizeF fSize = gfx.MeasureString(barcodeText, f);           
            gfx.DrawString(barcodeText, f, b, 0, PaddingTop);
            // Write numeric value
            Font f2 = new Font("Arial", numericFontSize);
            SizeF f2Size = gfx.MeasureString(requestedCode, f2);
            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
           // gfx.DrawString(requestedCode + "(" + price + ")", f2, b, 0, PaddingTop + fSize.Height);          
            gfx.DrawString(requestedCode, f2, b, (width/2)-f2Size.Width, PaddingTop + fSize.Height);          
            // Create a stream that will containt the bmp
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Gif);
            string s = Server.MapPath("~/Admin/BarCode/Images/");
            bmp.Save(s + requestedCode + ".gif");            
            ms.Close();
            bmp.Dispose();
        }
        private void CreateBarcode391(string requestedCode, string price)
        {
            //  return;
            const int PaddingTop = 0;
            const int CodeLenght = 16;

            string barcodeText = null;

            barcodeText = "*" + requestedCode.Trim() + "*";

            // Check for security 
            if ((requestedCode == null) || (requestedCode == string.Empty))
            {
                throw new Exception("200101");
                //Throw New ArgumentNullException(ParamCodeId, "200101")
            }
            if (requestedCode.Length > CodeLenght)
            {
                //Throw New ArgumentOutOfRangeException(ParamCodeId, "200100")

                throw new Exception("200100");


            }

            // Initialize values
            int barcodeFontSize = 30;
            int numericFontSize = 10;
            int width = 121;
            int height = 80;

            // Create bitmap

            Bitmap bmp = new Bitmap(width, height);
            // Create surface
            Graphics gfx = Graphics.FromImage(bmp);
            gfx.Clear(Color.White);

            // Set render mode
            gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;

            // Set brush type and color
            Brush b = Brushes.Black;

            // Load EAN font
            string sss = Server.MapPath("~/Admin/BarCode/Font/FREE3OF9.TTF");
            System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
            pfc.AddFontFile(sss);

            // Write barcode
            FontFamily ff = pfc.Families[0];
            Font f = new Font(ff, barcodeFontSize);
            SizeF fSize = gfx.MeasureString(barcodeText, f);
            // bmp = new Bitmap((int)fSize.Width+20, (int)fSize.Height + 10);
            //  gfx.DrawString(barcodeText, f, b, (width - Convert.ToInt32(width)) / 2, PaddingTop);
            gfx.DrawString(barcodeText, f, b, 0, PaddingTop);
            //  gfx.DrawString(barcodeText, f, b, (width - Convert.ToInt32(fSize.Width)) / 2, PaddingTop);


            // Write numeric value
            Font f2 = new Font("Arial", numericFontSize);
            SizeF f2Size = gfx.MeasureString(requestedCode, f2);
            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            gfx.DrawString(requestedCode + "(50000000)", f2, b, 0, PaddingTop + fSize.Height);
            // gfx.DrawString(requestedCode, f2, b, 0, 0);
            //  gfx.DrawString"Unit ", new Font("Arial", 10), Brushes.Red, 50, 50);
            // Create a stream that will containt the bmp
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Gif);
            string s = Server.MapPath("~/Admin/BarCode/Images/");
            bmp.Save(s + requestedCode + ".gif");
            // Send image to output stream
         //   Response.ContentType = "image/gif";
          //  ms.WriteTo(Response.OutputStream);
            // Response.Write("sadfsadsad")
            // Close and Free resources
            ms.Close();
            bmp.Dispose();
        }
        public void ExportBarCode128(string requestedCode, string price)
        {
           

            System.Drawing.Image img = GenCode128.Code128Rendering.MakeBarcodeImage(requestedCode, 1, 30, true, true, "arial", 11);
            string s = Server.MapPath("~/Admin/BarCode/Images/");           
            System.Drawing.Image img1=cropImage(img, new Rectangle(0,0,121,46));
            img1.Save(s + requestedCode + ".gif");
            
        }
        private System.Drawing.Image cropImage(System.Drawing.Image img, Rectangle cropArea)
        {
            Bitmap bmpImage = new Bitmap(img);
            Bitmap bmpCrop = bmpImage.Clone(cropArea,
            bmpImage.PixelFormat);
            return (System.Drawing.Image)(bmpCrop);
        }
    }
}
